package top.easyblog.core.scheduling;

import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.easyblog.core.annotation.CostTimeTracker;
import top.easyblog.core.annotation.RequestId;
import top.easyblog.core.atomic.AtomicCompressCodeService;
import top.easyblog.core.atomic.AtomicMappingVisitRecordService;
import top.easyblog.core.service.MappingVisitRecordService;
import top.easyblog.core.support.lock.DistributedLock;
import top.easyblog.core.support.lock.RedisDistributeLockFactory;
import top.easyblog.core.util.ConcurrentUtils;

/**
 * 定时任务统计数据
 *
 * @author <a href="https://github.com/dlmyL">dlmyL</a>
 * @version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VisitStatisticsTask {

    private final AtomicMappingVisitRecordService atomicMappingVisitRecordService;

    private final AtomicCompressCodeService atomicCompressCodeService;

    private final RedisDistributeLockFactory redisDistributeLockFactory;

    private final static String COMPRESSION_CODE_VISIT_STATISTICS_KEY = "dlock:compression-code-visit-statistic-key";


    @RequestId
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void processVisitStatistics() {
        ConcurrentUtils.executeTaskInNonBlockModel(Lists.newArrayList(this::doTask), null);
    }


    @CostTimeTracker
    public void doTask(){
        DistributedLock lock = redisDistributeLockFactory.getNonWaitingDistributedLock(COMPRESSION_CODE_VISIT_STATISTICS_KEY);
        boolean tryLock = false;
        try {
            tryLock = lock.lock();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if (tryLock) {
            try {
                System.out.println("VisitStatisticsTask");
            } catch (Exception e) {
                e.printStackTrace();
                log.warn("执行定时计算访问统计数据任务失败：" + e);
            } finally {
                lock.unlock();
            }
        }
    }

}
